package cz.worsik.android.test.rideshare.db;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

/**
 * Created by 231260 on 4.1.14.
 */
public class DbAdapter {

    private final Context context;

    private DatabaseHelper DbHelper;
    private SQLiteDatabase db;

    private SettingAdapter settings;
    private PaymentAdapter payments;
    private DriverAdapter drivers;
    private ContactAdapter contacts;
    private DrivewayAdapter driveways;

    public DbAdapter(Context ctx)
    {
        this.context = ctx;
        DbHelper = new DatabaseHelper(context);
    }

    //---opens the database---
    public DbAdapter open() throws SQLException
    {
        db = DbHelper.getWritableDatabase();
        settings = new SettingAdapter(db);
        payments = new PaymentAdapter(db);
        drivers = new DriverAdapter(db);
        //contacts = new ContactAdapter(db);
        driveways = new DrivewayAdapter(db);
        return this;
    }

    public int checkVersion(boolean reload)
    {
        int oldVersionMajor = 1;
        int oldVersionMinor = 0;
        Cursor c = db.query(true, "version", new String[] {
                "major", "minor"
        },
                null,
                null,
                null,
                null,
                null,
                null);
        if (c != null && c.moveToFirst()) {
            oldVersionMajor = c.getInt(0);
            oldVersionMinor = c.getInt(1);
        }
        c.close();

        int oldVersion = oldVersionMajor * 100 + oldVersionMinor;
        int newVersion = DbVersion.DATABASE_MAJOR_VERSION * 100 + DbVersion.DATABASE_MINOR_VERSION;

        if (oldVersion == newVersion)
        {
            return DbVersion.NO_VERSION_UPDATED;
        }
        else if(oldVersionMajor == DbVersion.DATABASE_MAJOR_VERSION)
        {
            // major verze se nezmenila, provedu jen onCreate
            DbHelper.onCreate(db);
            return DbVersion.MINOR_VERSION_UPDATED;
        }
        else
        {
            if (reload)
            {
                reload(oldVersion, newVersion);
                return DbVersion.MAJOR_VERSION_UPDATED;
            }
            else
            {
                return DbVersion.MAJOR_VERSION_NEED_UPDATE;
            }
        }
    }

    //---closes the database---
    public void close()
    {
        settings = null;
        payments = null;
        drivers = null;
        contacts = null;
        driveways = null;
        DbHelper.close();
    }

    public void reload(int oldVersion, int newVersion)
    {
        DbHelper.onUpgrade(db, oldVersion, newVersion);
    }

    public int getContactCount()
    {
        return 0;
    }
}
